using MediatR;
using Microsoft.AspNetCore.Mvc;
using WMS.ErrorCode;
using WMS.WebApiWrite.Application.Command;

namespace WMS.WebApiWrite.Controllers
{
    /// <summary>
    /// 盘点信息写操作控制器
    /// </summary>
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class InventoryController : ControllerBase
    {
        private readonly IMediator mediator;
        private readonly ILogger<InventoryController> logger;

        /// <summary>
        /// 构造函数，注入MediatR和日志服务
        /// </summary>
        public InventoryController(IMediator mediator, ILogger<InventoryController> logger)
        {
            this.mediator = mediator;
            this.logger = logger;
        }

        /// <summary>
        /// 保存盘点信息（新增或编辑）
        /// 包含盘点主表、盘点明细（批量）、上传附件（批量）
        /// 使用事务确保三个表同时成功或失败
        /// </summary>
        /// <param name="command">保存盘点命令</param>
        /// <returns>返回操作结果，Data为盘点编号</returns>
        [HttpPost]
        public async Task<ApiResult<string>> SaveInventory([FromBody] SaveInventoryCommand command)
        {
            var isEdit = command.InventoryDTO.InventoryId.HasValue && command.InventoryDTO.InventoryId.Value > 0;
            
            logger.LogInformation($"开始{(isEdit ? "编辑" : "新增")}盘点信息，" +
                                $"明细数量：{command.InventoryDTO.DetailsList?.Count ?? 0}，" +
                                $"附件数量：{command.InventoryDTO.AttachmentList?.Count ?? 0}，" +
                                $"操作人：{command.InventoryDTO.OperatorName}");

            var result = await mediator.Send(command);

            logger.LogInformation($"{(isEdit ? "编辑" : "新增")}盘点信息完成，结果：{result.Message}");

            return result;
        }

        /// <summary>
        /// 删除盘点信息（逻辑删除）
        /// 使用事务同时逻辑删除盘点表、盘点明细表、上传附件表
        /// </summary>
        /// <param name="command">删除盘点命令</param>
        /// <returns>返回操作结果</returns>
        [HttpPost]
        public async Task<ApiResult<bool>> DeleteInventory([FromBody] DeleteInventoryCommand command)
        {
            logger.LogInformation($"开始删除盘点信息，盘点ID：{command.InventoryId}，操作人：{command.OperatorName}");

            var result = await mediator.Send(command);

            logger.LogInformation($"删除盘点信息完成，结果：{result.Message}");

            return result;
        }
    }
}

